// arduino script for singlee MMG input, focusing on the RMSing of values every 
// 100 or so samples. This one gives the data through as continuous string as well
// Written by Edward Brial 

#include <stdio.h>
#include <Wire.h>
#include <math.h>
#include "filter.h"

#define RMSsize 50      // Sample size of RMS window, up here so it's easy to change
#define Baud 115200
//call prototypes & global variables
int RMSfun (short* readings, int length)

	unsigned long lastmeasure;
int RMSfinal;
short tempread[RMSsize];
short filtarray[RMSsize];


void setup(void){
	Wire.begin(0x02); //the address will need to be specified at some point!!
	Wire.onrequest(sendRMS);

	Serial.begin(Baud);
	while(!Serial.available());

}

void loop(void){

	float result;

	int i;
	while 1 {

		for (i=0 , i < RMSsize, i++) { //i++ = unit increment every loop
			lastmeasure = micros(); // starts lastmeasure from micros current timing point
			tempread[i] = analogRead(A0);
			while (micros() < lastmeasure + 1250) ; // waits for 1250microsecs before next reading
		}

		filter(tempread, filtarray, RMSsize); //Data array will be filtered
		RMSfinal = RMSfun(filtarray, RMSsize);   //RMS value of Data Array

		Serial.print(micros());
		Serial.print(",");
		Serial.println(RMSfinal);

	}
}


// I2C subroutine
void sendRMS (void) {
	Wire.send(RMSfinal); // stores the RMSfinal value in the wire send buffer, ready for the call!
	Wire.endTransmission();   // is this part necessary? 
}

// function to be written to take the moving rms of each temp sample.
int RMSfun (short* readings, int length){
	int j;
	int Sum = 0;
	int RmsVal;

	for (j=0 , j < length, j++) {
		readings[j] = readings[j]*readings[j]; //squares all the individual values. rms = sqrt(1/n(sum(xi^2)))
		Sum = Sum + readings[j];
	}
	RmsVal = sqrt(Sum/length);

	return RmsVal;
}





